package com.wxd.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

// 这个注解是指定哪些Controller可以被拦截
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
// @ResponseBody和@ControllerAdvice这两个注解可以用@RestControllerAdvice代替
public class GlobalExceptionHandle {
    // 指定拦截哪一类异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandle(SQLIntegrityConstraintViolationException e) {
        // 因为sql的异常有好多种 所以要做分类
        if (e.getMessage().contains("Duplicate entry")) {
            String[] ss = e.getMessage().split(" ");
            String errMsg = ss[2] + " 已存在";
            return R.error(errMsg);
        }
        return R.error("未知错误");
    }

    // 拦截业务异常
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandle(CustomException e) {
        return R.error(e.getMessage());
    }
}
